<template>
  <div class="set-approval">
    <a-row class="step-header" align="middle">
      <a-col :span="12" :offset="6">
        <a-steps v-model:current="currentStep" type="navigation">
          <a-step
            v-for="step of stepList"
            :key="step.step"
            :title="step.title"
          />
        </a-steps>
      </a-col>
      <a-col :span="6" style="text-align: right">
        <a-space>
          <a-popover
            v-model:visible="showErrorInfo"
            title="内容不完善"
            trigger="click"
          >
            <template #content>
              <div class="error-info">
                <div
                  class="error-tip"
                  v-for="(error, index) of errorInfo"
                  :key="index"
                >
                  <div style="margin-right: 10px">
                    <span class="title">{{ getTitleByStep(error.step) }}</span>
                    <span class="tip">{{ error.tip }}</span>
                  </div>
                  <a-button
                    type="link"
                    @click="goErrorStep(error)"
                    v-if="currentStep != error.step"
                  >
                    去完善
                  </a-button>
                </div>
              </div>
            </template>
            <a-button
              type="link"
              danger
              @click="showErrorInfo = true"
              v-if="errorInfo.length"
            >
              {{ errorInfo.length }}项不完善
            </a-button>
          </a-popover>
          <!-- <a-button>预览</a-button> -->
          <a-button type="primary" @click="submit" :loading="submitLoading">
            发布
          </a-button>
        </a-space>
      </a-col>
    </a-row>
    <section class="notice" v-if="detail.alias && currentStep < 2">
      该审批由【{{
        detail.from_third
      }}】提供，部分信息不支持修改，如需修改请联系【{{
        detail.from_third
      }}】应用
    </section>
    <section class="content beauty-scroller-bar">
      <!-- 基础信息 -->
      <BasicInfo
        v-show="currentStep == 0"
        :trigger="trigger"
        @triggerChange="getBasicInfo"
      />
      <!-- 表单设计 -->
      <FormDesign
        v-show="currentStep == 1"
        :trigger="trigger"
        @triggerChange="getFormDesign"
        :formType="detail.alias"
      />
      <!-- 流程设计 -->
      <ProcessDesign
        v-show="currentStep == 2"
        :isFromOther="detail.alias != undefined && detail.alias != ''"
        :trigger="trigger"
        @triggerChange="getProcessDesign"
      />
      <!-- 更多设置 -->
      <MoreSetting
        v-show="currentStep == 3"
        :trigger="trigger"
        @triggerChange="getMoreSetting"
      />
    </section>
  </div>
</template>

<script>
import {
  computed,
  defineComponent,
  nextTick,
  reactive,
  toRaw,
  toRefs,
  watch,
} from "vue";
import { Steps, Step, message } from "ant-design-vue";
import BasicInfo from "./modules/BasicInfo.vue";
import FormDesign from "./modules/FormDesign.vue";
import ProcessDesign from "./modules/ProcessDesign.vue";
import MoreSetting from "./modules/MoreSetting.vue";
import common from "./js/common";
import request from "../../../common/utils/request";
import store from "../../../store";
import { useRoute, useRouter } from "vue-router";
import _ from 'lodash'
import utils from '@/common/utils/utils'

const stepList = [
  { step: 0, title: "基础信息" },
  { step: 1, title: "表单设计" },
  { step: 2, title: "流程设计" },
  { step: 3, title: "更多设置" },
];

export default defineComponent({
  name: "SetApproval",
  components: {
    "a-steps": Steps,
    "a-step": Step,
    BasicInfo,
    FormDesign,
    ProcessDesign,
    MoreSetting,
  },
  setup() {
    const router = useRouter();
    const route = useRoute();

    const state = reactive({
      id: route.query.id,
      currentStep: 0,
      trigger: 0,
      showErrorInfo: false,
      errorBasicInfo: [],
      errorFormDesign: [],
      errorProcessDesign: [],
      submitData: {},
      submitLoading: false,
      finishedCount: 0,
      detail: {},
      lastMicroId: route.query.microId||"Approval"
    });

    watch(
      () => state.currentStep,
      (step) => {
        state.finishedCount = 0;
        state.trigger++;
        store.dispatch("SetCurrentStep", step);
      }
    );

    const errorInfo = computed(() => [
      ...state.errorBasicInfo,
      ...state.errorFormDesign,
      ...state.errorProcessDesign,
    ]);

    const getTitleByStep = (step) => {
      const result = stepList.find((item) => item.step == step);
      return result.title;
    };

    // 获取基础信息
    const getBasicInfo = (info) => {
      console.log("-------------getBasicInfo", toRaw(info));
      state.errorBasicInfo = [];
      const step = 0;
      if (!info.name) {
        state.errorBasicInfo.push({
          step,
          tip: "未填写审批名称",
        });
      }
      if (!info.cat_id) {
        state.errorBasicInfo.push({
          step,
          tip: "未选择审批所属分组",
        });
      }
      if (!info.admin_users.length) {
        state.errorBasicInfo.push({
          step,
          tip: "未选择审批流程管理员",
        });
      }
      state.finishedCount++;
      state.submitData = {
        ...state.submitData,
        ...info,
      };
    };

    // 获取表单设计数据
    const getFormDesign = (list) => {
      console.log("-------------getFormDesign", toRaw(list));
      if (!list.length && state.currentStep > 1) {
        message.warning("请至少设置一个表单项！");
      }
      let step = 1;
      state.errorFormDesign = [];
      if (!list.length) {
        state.errorFormDesign.push({
          step,
          tip: "至少需要一个控件",
        });
      } else {
        state.errorFormDesign = common.getFormDesignErrorInfo(list);
      }
      state.finishedCount++;
      state.submitData.form = list;
    };

    // 获取流程设计数据
    const getProcessDesign = (list) => {
      console.log("-------------getProcessDesign", toRaw(list));
      state.errorProcessDesign = [];
      if (list.length==2) {
        state.errorProcessDesign.push({
          step: 2,
          tip: "至少需要添加一个审批流程",
        });
      } else {
        state.errorProcessDesign = common.getProcessDesignErrorInfo(list);
      }
      state.finishedCount++;
      state.submitData.process = list;
    };

    // 获取更多设置
    const getMoreSetting = (info) => {
      console.log("-------------getMoreSetting", toRaw(info));
      state.finishedCount++;
      state.submitData = {
        ...state.submitData,
        ...info,
      };
    };

    watch(
      [() => state.finishedCount, () => state.submitLoading],
      ([count, loading], [preCount, preLoading]) => {
        if (preLoading != loading) {
          store.dispatch("SetSubmitLoading");
        }
        if (loading && count == 4) {
          if (errorInfo.value.length) {
            state.showErrorInfo = true;
            state.submitLoading = false;
          } else {
            submitInfo();
          }
        }
      }
    );

    const submit = () => {
      state.submitLoading = true;
      state.finishedCount = 0;
      state.trigger++;
    };

    const closeCurrentTab = () => {
      const microId = window.microApp?.appName
      utils.closeMicroAppPage(state.lastMicroId).then(()=>{
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: state.lastMicroId,
            app: 'workApproval',
            name: "审批管理",
            url: "/tenantApproval/manage/index",
          }
        })

        setTimeout(()=>{
          utils.closeMicroAppPage(microId)
        },200)
      })

    }

    const submitInfo = () => {
      const params = {
        ...state.submitData,
        needMsg: true,
      };
      delete params.adminUserList;
      console.log(
        "-------------submitsubmitsubmitsubmitsubmitsubmit--------------",
        toRaw(params)
      );
      let requestMethod = "post";
      let url = "/tenant/approval/add";
      if (state.id) {
        requestMethod = "put";
        params.id = state.id;
        url = "/tenant/approval/update";
      }
      request[requestMethod]("/work_approval", url, params)
        .then((res) => {
          message.success("保存成功！");
         setTimeout(()=>{
           closeCurrentTab()
         },1000)
        })
        .finally(() => {
          state.submitLoading = false;
        });
    };

    // 去完善
    const goErrorStep = (error) => {
      state.currentStep = error.step;
      state.showErrorInfo = false;
    };

    // 获取详情
    const getDetail = () => {
      request
        .get("/work_approval", "/tenant/approval/get", {
          id: state.id,
        })
        .then((res) => {
          state.detail = res.result;
          store.dispatch("SetDetail", res.result);
        });
    };

    const init = () => {
      if (state.id) {
        getDetail();
      } else {
        store.dispatch("SetDetail", {});
      }
    };

    init();

    return {
      errorInfo,
      stepList,
      ...toRefs(state),
      getBasicInfo,
      getFormDesign,
      getProcessDesign,
      getMoreSetting,
      getTitleByStep,
      goErrorStep,
      submit,
    };
  },
});
</script>

<style lang="less" scoped>
.set-approval {
  height: 100%;
  background: #f7f7f7;
  overflow: hidden auto;
  display: flex;
  flex-direction: column;
  box-shadow: @box-shadow-base;
  .step-header {
    background: #fff;
    height: 68px;
    padding: 10px 20px 0 20px;
  }
  .notice {
    line-height: 40px;
    background: #feead2;
    color: #333;
    text-align: center;
  }
  .content {
    flex: 1;
    overflow: hidden auto;
  }
}
.error-info {
  width: 400px;
  background: #fff;

  .error-tip {
    height: 45px;
    line-height: 45px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #f7f7f7;
    padding: 0 10px;
    margin-bottom: 12px;
    .title {
      color: #333;
      font-weight: bold;
    }
    .tip {
      color: #999;
      margin: 0 12px;
    }
  }
}
</style>
